from fastapi import APIRouter, WebSocket,WebSocketDisconnect
from typing import List
from apps.models import Question,Course
from apps.schemas.qusetion import QuesstionResponse,QuestionCreate,NumResponse,ImgCreate
import json
question = APIRouter ()
@question.get("/get_stu_course_message/{extral_2}", response_model=List[QuesstionResponse])
async def get_stu_course_message(extral_2: str):
    """
    获取聊天内容
    """
    content = await Question.filter(extral_2=extral_2).select_related("user_id").order_by("send_time")
    return content

@question.post("/add_stu_course_message")
async def add_stu_course_message(body: QuestionCreate):
    """
    添加学生讨论信息
    """
    await Question.create(**body.dict())
    return {"code": 200, "message": "添加成功"}

@question.get("/get_stu_course_num/{extral_2}", response_model=List[NumResponse])
async def get_stu_course_num(extral_2: str):
    """
    获取课程人数
    """
    num = await Course.filter(extral_2=extral_2).prefetch_related("user_id__login_id")
    return num

@question.post("/upload_image")
async def upload_image(body: ImgCreate):
    """
    上传图片
    """
    print(body.dict())

# websocket聊天
connect_chat = []
@question.websocket("/ws/{ID}/{courseID}")
async def ws(websocket: WebSocket, ID: str, courseID: str):
    await websocket.accept()
    connect_chat.append(websocket)
    # 1. 发送进入聊天室的JSON消息
    join_message = {
        "content": f"欢迎{ID}已进入{courseID}聊天室",
    }
    await websocket.send_text(json.dumps(join_message))  # 转换为JSON字符串发送

    try:
        while True:
            # 接收前端发送的JSON消息（假设前端也发送JSON）
            data = await websocket.receive_text()
            # 解析前端消息（如果需要）
            received_data = json.loads(data)
            print(received_data)
            data_ = {
                "content": received_data.get("content", ""),
                "send_time": received_data.get("send_time", ""),
                "extral_2": received_data.get("extral_2", ""),
                "user_id_id": received_data.get("user_id", {}).get("id", ""),
            }
            try:
                await Question.create(**data_)
            except Exception as e:
                # 处理数据库操作异常
                error_message = {
                    "type": "error",
                    "content": "消息保存失败"
                }
                await websocket.send_text(json.dumps(error_message))
                continue
            # 2. 广播用户发送的消息（JSON格式）
            broadcast_message = {
                "content": received_data.get("content", ""),  # 提取消息内容
                "send_time": received_data.get("send_time", ""),
                "extral_2": received_data.get("extral_2", ""),
                "user_id": {
                    "id": received_data.get("user_id", {}).get("id", ""),
                    "name": received_data.get("user_id", {}).get("name", "")
                }
            }
            # 向所有连接的客户端广播JSON消息
            for client in connect_chat:
                await client.send_text(json.dumps(broadcast_message))

    except WebSocketDisconnect:
        connect_chat.remove(websocket)
        # 3. 发送离开聊天室的JSON消息
        leave_message = {
            "type": "status",
            "user": ID,
            "course": courseID,
            "content": f"{ID}已离开聊天室",
        }
        for client in connect_chat:
            await client.send_text(json.dumps(leave_message))
    except json.JSONDecodeError:
        # 处理前端发送的非JSON格式消息
        error_message = {
            "type": "error",
            "content": "无效的消息格式，请发送JSON"
        }
        await websocket.send_text(json.dumps(error_message))
